﻿
using LibNiconico.NiconicoApi.Utils;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using System.Xml;
using LibNiconico.NiconicoApi.Sgml;
using LibNiconico.NiconicoApi.Internal.Http;

namespace LibNiconico.NiconicoApi.Internal
{
    /// <summary>
    /// HTML形式で情報を取得するニコニコAPI
    /// </summary>
    internal class NiconicoInfoGetApiHtmlImpl:NiconicoInfoGetApiImpl

    {
        internal NiconicoInfoGetApiHtmlImpl(Uri url, INiconicoHttpClient api) : base(url, api) { }

        /// <summary>
        /// Getメソッドで非同期に情報を取得する
        /// </summary>
        /// <param name="urlAble"></param>
        /// <returns></returns>
        internal async Task<NiconicoHttpResponse<XDocument>> GetAsync(NicoUrlAble urlAble)
        {
            var response = await base.GetStreamAsync(urlAble).ConfigureAwait(false);
            return NiconicoHttpResponse.ConvertContent( parse(response.Content),response);
        }

        /// <summary>
        /// Postメソッドで非同期に情報を取得する
        /// </summary>
        /// <param name="postAble"></param>
        /// <returns></returns>
        internal async Task<NiconicoHttpResponse<XDocument>> PostAsync(NicoPostAble postAble)
        {
            var response = await base.PostStreamAsyunc(postAble).ConfigureAwait(false);
            return NiconicoHttpResponse.ConvertContent( parse(response.Content),response);
        }


        private static XDocument parse(Stream stream)
        {
            using (SgmlReader reader = new SgmlReader() { InputStream = new StreamReader(stream), DocType = "html", CaseFolding = CaseFolding.ToLower,IgnoreDtd = true })
            {
                
                return XDocument.Load(reader);
            }
        }
    }
}
